package com.example.tkserver.service.impl;

import com.example.tkserver.dao.RedisCacheDao;
import com.example.tkserver.dao.SignInHistoryDao;
import com.example.tkserver.dao.UserDao;
import com.example.tkserver.service.interfaces.SignInService;
import com.example.tkserver.entity.MyException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Log4j2
public class SignInServiceImpl implements SignInService {

    @Autowired
    SignInHistoryDao historyDao;

    @Autowired
    UserDao userDao;

    @Autowired
    RedisCacheDao redisCacheDao;

    @Override
    public int signIn(int uid) {
        // 如果今天没有签到过
        if (historyDao.getSignInByToday(uid) == null){
            Integer endorse = redisCacheDao.getObject("signInEndorse",Integer.class);
            if (endorse == null){
                endorse = 100;
                redisCacheDao.add("signInEndorse",100);
            }
            // 添加签到记录
            if (historyDao.addNewSignInToday(uid,endorse) != -1){
                // 添加积分
                if (userDao.addScores(uid,endorse) != -1){
                    return endorse;
                }else{
                    throw new MyException("签到失败！请联系管理员进行反馈！");
                }
            }else{
                throw new MyException("签到失败！请联系管理员进行反馈！");
            }
        }
        throw new MyException("您今天已签到！");
    }
}
